package com.dwxt.mall.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.IDUtils;
import com.dwxt.common.zfbpay.ZFBConfig;
import com.dwxt.mall.constant.OrderStatus;
import com.dwxt.mall.entity.PayOrder;
import com.dwxt.mall.entity.Product;
import com.dwxt.mall.service.feign.PayService;
import com.dwxt.mall.service.feign.RedisService;
import com.dwxt.mall.service.feign.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ZFBService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private PayService payService;

    @Value("${mall.zfb.notifyUrl}")
    private String notifyUrl;

    @Autowired
    private UserService userService;

    @Transactional
    public BaseResult createOrderWithZFB(PayOrder order) throws AlipayApiException {

        //校验产品和订单
        Product product = productService.selectProductByPrimaryKey(order.getProductId());
        BaseResult result = orderService.validOrder(order, product);
        if (result != null) return result;
        //生成微信预付订单
        String orderId = IDUtils.genItemId();
        Double realPrice = order.getRealPrice();
        String zfbPayString = "";
        if (realPrice > 0) {
            //respData = createPaymentOrderReadyWX(order, ip, null);
            //构造请求参数，请求微信支付
            Map<String, String> params = buildReqParams(orderId, realPrice);
            BaseResult baseResult = payService.payWithZFB(params);
            zfbPayString = baseResult.getData().toString();
            //生成本地订单
            orderService.createOrderLocal(order, product, orderId, zfbPayString);
            //订单存入redis
            redisService.set("mall_" + order.getId(), order.getId(), (long) 15 * 60);
        } else {
            //生成本地订单
            orderService.createOrderLocal(order, product, orderId, zfbPayString);
            //更改用户积分，生成积分记录,消耗积分
            userService.updateIntegral(-order.getIntegral(), order.getId(), order.getName(), order.getUserId());
        }
        Map map = new HashMap();
        map.put("orderId", order.getId());
        map.put("orderString", zfbPayString);
        return BaseResult.ok(map);
    }


    private Map<String, String> buildReqParams(String orderId, Double realPrice) {
        Map<String, String> params = new HashMap<>();
        params.put("notifyUrl", notifyUrl);
        params.put("orderId", orderId);
        params.put("type", "1");
        params.put("price", realPrice.toString());
        return params;
    }


    public String checkParamsZFB(Map<String, String> params) throws AlipayApiException {
        //PayAccount account = payAccountService.selectEffectivePayAccount(PurchaseMethod.ZFB);
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ZFBConfig.publicKey, ZFBConfig.charset, ZFBConfig.signType);
        //对验签进行处理
        log.info("result:1");
        if (signVerified) {  //验签通过
            String out_trade_no = params.get("out_trade_no");// 商户订单号
            PayOrder order = orderService.selectByPrimaryKey(out_trade_no);
            if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {//只处理支付成功的订单: 修改交易表状态,支付成功
                if (!order.getStatus().equalsIgnoreCase(OrderStatus.PLACE)) {
                    log.info("result:2");
                    return "success";
                }
                //业务处理
                String tradeStatus = params.get("trade_status");
                String total_amount = params.get("total_amount");
                if (order != null && order.getRealPrice() == Double.parseDouble(total_amount)) {
                    log.info("result:3");
                    orderService.changUserInfoWithWxAndZFBPay(order);
                    return "success";
                }
                log.error(out_trade_no + " : " + total_amount + " : " + tradeStatus);
            } else {
                log.info("result:4");
                //库存增加,订单失败
                orderService.cancelOrfailOrder(order, OrderStatus.Fail);
            }
        }
        log.info("result:5");
        return "fail";
    }
}
